$KCODE = 'u'
module ExceptionSend
  
  def self.included(target)
    target.extend(ClassMethods)
  end
  
  module ClassMethods
    
    def before_es_config
      @es_email_prefix = ExceptionNotifier.email_prefix
      @es_email = ExceptionNotifier.exception_recipients
    end
    
    def after_es_config
      ExceptionNotifier.email_prefix = @es_email_prefix
      ExceptionNotifier.exception_recipients = @es_email
    end
    
    def email_suffix
      "@alpha-it-system.com"
    end
    
    def es_title
      "【 您的BUG: 】"  
    end
    
    def es_config
      {
        "rsh" => ["zk", "hzy"],
        "hx" => ["zs", "whl", "lgl"],
        "sx" => ["tmy", "ww", "ljl"]
      }
    end
    
    def es_get_name(controller, action)
      file_name = controller + "_controller.rb"
      path = File.join(RAILS_ROOT, "app", "controllers", file_name)#
      text = File.read path
      $1 if text =~ /#\s*【著作】\s*by\s*(\w+)\s*.*\n\s*def\s+#{action}/
    end
    
    def es_get_email(name)
      emails = [[name.to_s.downcase, email_suffix].join("")]
      es_config.each do|k, v|
        next if !v.is_a?(Array)
        if v.include? name
          emails << [k.to_s, email_suffix].join("")
          break 
        end
      end
      emails
    end
  
    def get_default_email
      es_config.keys.collect{|se| [se.to_s, email_suffix].join("") }
    end
  
    def additional_data(controller, action)
      
      before_es_config
      
      name = es_get_name(controller, action)
      email = es_get_email(name) if name.present?
      email = get_default_email if email.blank?
      ExceptionNotifier.exception_recipients = email 
      ExceptionNotifier.email_prefix = es_title
    end
    
  end

  private
  
  def rescue_action_in_public(exception)
      case exception
        when *self.class.exceptions_to_treat_as_404
          render_404
        else          
          render_500
          deliverer = self.class.exception_data
          data = case deliverer
            when nil then {}
            when Symbol then send(deliverer)
            when Proc then deliverer.call(self)
          end
          
          ExceptionNotifier.deliver_exception_notification(exception, self,
            request, data)
          
          self.class.additional_data(params[:controller], params[:action])
          
          ExceptionNotifier.deliver_exception_notification(exception, self,
            request, data)
            
          self.class.after_es_config
            
      end
    end

end
